#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>

#include "train_trans.h"

int train_send(const int fd, const void *data, int length) {
  train_t train;
  bzero(&train, sizeof(train));
  train.length = length;
  memcpy(train.data, data, train.length);
  int ret = send(fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
  return ret;
}

int recvn(const int fd, void *buf, int length) {
  int total = 0;
  int ret;
  char *p = (char *)buf;
  while (total < length) {
    ret = recv(fd, p + total, length - total, 0);
    if (ret == 0) {
      return total;
    }
    total += ret;
  }
  return total;
}

int train_recv(const int fd, void *data, const int max_length) {
  train_t train;
  bzero(&train, sizeof(train_t));
  recvn(fd, &train.length, sizeof(int));
  recvn(fd, &train.data, train.length);
  if (max_length < train.length) {
    return -1;
  }
  memcpy(data, train.data, train.length);
  return train.length;
}
